package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xiaomi-hub/cache"
	"xiaomi-hub/models"
	"xiaomi-hub/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user models.User
	redis_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	err := models.DB.Where("username =?", username).First(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查找失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码有误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	title := c.Query("title")
	var good []models.Good
	redis_key := "list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Where("title = ?", "%"+title+"%").Find(&good)
		jsonData, _ := json.Marshal(good)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &good)
	}
	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  good,
		"count": count,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	price := c.PostForm("price")
	good := models.Good{
		Title:   title,
		Content: content,
		Price:   price,
	}
	err := models.DB.Create(&good).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func GoodList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	title := c.Query("title")
	var good []models.Good
	redis_key := "list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Where("title = ?", "%"+title+"%").Find(&good)
		jsonData, _ := json.Marshal(good)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &good)
	}
	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  good,
		"count": count,
	})
	return
}
